/*
   Copyright (c) 2017 TOSHIBA Digital Solutions Corporation

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package com.toshiba.mwcloud.gs;

import java.util.Arrays;

import com.toshiba.mwcloud.gs.common.BasicBuffer;
import com.toshiba.mwcloud.gs.common.GSErrorCode;
import com.toshiba.mwcloud.gs.common.GeometryUtils;
import com.toshiba.mwcloud.gs.common.GeometryUtils.DirectAccessor;

/**
 * Manages the geometry data which represents geometry range of two or three
 * dimensions.
 *
 * <p>An instance of this class are immutable. In addition, all method calls to
 * an instance of this class are thread safe.</p>
 */
public class Geometry {

	static {
		GeometryUtils.setDirectAccessor(new DirectAccessor() {

			@Override
			public int getBytesLength(Geometry geometry) {
				return geometry.bytesData.length;
			}

			@Override
			public void putGeometry(BasicBuffer out, Geometry geometry) {
				out.prepare(geometry.bytesData.length);
				out.base().put(geometry.bytesData);
			}

			@Override
			public Geometry getGeometry(BasicBuffer in, int size) {
				final byte[] bytesData = new byte[size];
				in.base().get(bytesData);
				return new Geometry(bytesData);
			}

		});
	}

	private final byte[] bytesData;

	private Geometry(byte[] bytesData) {
		this.bytesData = bytesData;
	}

	/**
	 * Creates the {@link Geometry} from the string representation
	 * (WKT representation) to geometry data in WKT (Well-Known Text) format.
	 *
	 * <p>Supported WKT representation is the same as the representation range
	 * to be handled by {@code ST_GeomFromText} function in TQL. However,
	 * the geometry structure {@code QUADRATICSURFACE} can only be used as
	 * search condition and not to be stored in the container.</p>
	 *
	 * @param value WKT representation to be created. {@code null} cannot be specified
	 *
	 * @return Instance of {@link Geometry} created by WKT representation
	 *
	 * @throws IllegalArgumentException If the specified string does not match
	 * to the WKT format
	 * @throws IllegalArgumentException when {@code null} is specified as argument
	 */
	public static Geometry valueOf(String value)
			throws IllegalArgumentException {
		try {
			return new Geometry(GeometryUtils.encodeGeometry(value));
		}
		catch (GSException e) {
			throw new IllegalArgumentException(
					"Illegal geometry format (value=\"" + value + "\", " +
					"reason=" + e.getMessage() + ")", e);
		}
		catch (NullPointerException e) {
			throw GSErrorCode.checkNullParameter(value, "value", e);
		}
	}

	/**
	 * Returns the string representation (WKT representation) in WKT
	 * (Well-Known Text) format.
	 *
	 * <p>Returned string may not be equivalent to the specified WKT
	 * representation when generated by {@link #valueOf(String)}, if there are
	 * inconsistent spelling such as blank character as a delimiter or the
	 * default SRID values.</p>
	 */
	@Override
	public String toString() {
		try {
			return GeometryUtils.decodeGeometry(bytesData);
		}
		catch (GSException e) {
			throw new Error(
					"Internal error or decode error of remote data (reason=" +
					e.getMessage() + ")", e);
		}
	}

	/**
	 * Returns the hash code of this object.
	 *
	 * <p>This method maintain the general contract for the
	 * {@link Object#hashCode()} method, which states that equal objects must
	 * have equal hash codes.</p>
	 *
	 * @return Hash code of this object
	 *
	 * @see #equals(Object)
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + Arrays.hashCode(bytesData);
		return result;
	}

	/**
	 * Indicates whether some other object is "equal to" this one.
	 *
	 * <p>Objects generated by {@link #valueOf(String)} and have no notation
	 * difference except inconsistent spelling such as blank character as a
	 * delimiter or the default SRID values are considered to be equivalent
	 * even if WKT representation of the source is not equivalent to each other
	 * as a string.
	 * For example, objects generated with the following three WKT
	 * representation are considered to be equivalent.</p>
	 * <pre>
	 * POLYGON((0 0,10 0,10 10,0 10,0 0))
	 * POLYGON( (0 0,10 0,10 10,0 10,0 0) )
	 * POLYGON((0 0,10 0,10 10,0 10,0 0);-1)</pre>
	 *
	 * <p>On the other hand, objects which have no equivalent WKT representation
	 * as a string because of the difference in the start/end position to the
	 * closed line that make up the area are considered not to be equivalent
	 * even if they indicate to the same space region.
	 * For example, objects generated with the following two WKT representation
	 * are considered not to be equivalent.</p>
	 * <pre>
	 * POLYGON((0 0,10 0,10 10,0 10,0 0))
	 * POLYGON((0 10,0 0,10 0,10 10,0 10))</pre>
	 *
	 * <p>This method maintain the general contract for the
	 * {@link Object#hashCode()} method, which states that equal objects must
	 * have equal hash codes.</p>
	 *
	 * @param obj The reference object to be compared
	 *
	 * @return {@code true} if this object is equal to {@code obj}, otherwise
	 * {@code false}
	 *
	 * @see #hashCode()
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Geometry other = (Geometry) obj;
		if (!Arrays.equals(bytesData, other.bytesData))
			return false;
		return true;
	}

}
